<template>
  <div class="login-account">
    <el-form label-width="60px" :rules="rules" :model="account" ref="formRef">
      <el-form-item label="账号" prop="username">
        <el-input v-model="account.username"> </el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password> </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { rules } from '../config/login-form-config'
import { ElForm } from 'element-plus'
import localCache from '@/utils/cache'
import { useStore } from 'vuex'

export default defineComponent({
  setup() {
    const store = useStore()
    const formRef = ref<InstanceType<typeof ElForm>>()
    const account = reactive({
      username: localCache.getCache('username') ?? '',
      password: localCache.getCache('password') ?? ''
    })

    const loginAction = (isKeepPassword: boolean) => {
      formRef.value?.validate((valid) => {
        console.log('账号登录表单验证结果：', valid)
        console.log('记住密码：', isKeepPassword)

        if (isKeepPassword) {
          // 勾选了记住密码，则保存到 localStorage
          localCache.setCache('username', account.username)
          localCache.setCache('password', account.password)
        } else {
          localCache.removeCache('username')
          localCache.removeCache('password')
        }

        // 调用 vuex 模块内的方法执行登录
        store.dispatch('login/accountLoginAction', { ...account })
      })
    }

    return { account, rules, loginAction, formRef }
  }
})
</script>
<style scoped></style>
